package com.ticket.service.impl;

import com.ticket.mapper.UserMapper;
import com.ticket.pojo.PageBean;
import com.ticket.pojo.User;
import com.ticket.service.UserService;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    @Override
    public void add(User user) {
        userMapper.add(user);

    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public void deleteById(int id) {
        userMapper.deleteById(id);
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    public void deleteByIds(int[] ids) {
        userMapper.deleteByIds(ids);
    }

    @Override
    public PageBean<User> selectByPage(int currentPage, int pageSize) {
        List<User> users = userMapper.selectByPage((currentPage - 1) * pageSize, pageSize);
        int totalCount = userMapper.selectTotalCount();

        //封装
        PageBean<User> pageBean = new PageBean<>();
        pageBean.setRows(users);
        pageBean.setTotalCount(totalCount);

        return pageBean;
    }

    @Override
    public PageBean<User> selectByPageAndCondition(int currentPage, int pageSize, User user) {
        //起始索引begin, 每页数据个数size
        //处理user条件，模糊表达式
        String name = user.getName();
        if (name != null && name.length() != 0) {
            System.out.println(name.length());
            user.setName("%" + name + "%");
        }

        String sex = user.getSex();
        if (sex != null && sex.length() != 0) {
            user.setSex("%" + sex + "%");
        }

        List<User> users = userMapper.selectByPageAndCondition((currentPage - 1) * pageSize, pageSize, user);
        int totalCount = userMapper.selectTotalCountByCondition(user);

        System.out.println(users);
        System.out.println(totalCount);
        //5.封装
        PageBean<User> pageBean = new PageBean<>();
        pageBean.setRows(users);
        pageBean.setTotalCount(totalCount);

        return pageBean;
    }
}
